package com.gopay.bis.service.bank.impl.ebank;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;

import com.gopay.bis.common.util.BankLogUtils;
import com.gopay.bis.common.util.BisPayCheckUtils;
import com.gopay.bis.common.util.constants.BisPayConstants;
import com.gopay.bis.manager.bank.ebank.UnionPayManager;
import com.gopay.common.Result;
import com.gopay.common.constants.bank.UnionPayConstants;
import com.gopay.common.constants.bank.UnionPayOrderStatus;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.unionpay.ebank.UnionPayMessage;
import com.gopay.common.exception.GopayException;
import com.gopay.common.util.MoneyUtil;
import com.gopay.remote.bank.BankInteractRemoteService;

/**
 * 民生银联业务实现
 * 
 * UnionPayBankServiceImpl.java
 * @author LILILI
 */
public class UnionPayBankServiceImpl implements BankInteractRemoteService  {
	
	@Resource(name = "unionPayManager")
	UnionPayManager unionPayManager;
    
	@Override
	public Result pay(BaseMessage base) {
		Result result = new Result(false);
		UnionPayMessage message = new UnionPayMessage();
		BeanUtils.copyProperties(base, message);
		try{
			message = (UnionPayMessage)unionPayManager.sign(message);
	        result.setDefaultModel(message);
	        result.setSuccess(true);	
		}catch (GopayException e) {
			BankLogUtils.printServiceImplExceptionLog(e);
    		result.setResultCode(e.getErrCode());
		}catch(Exception ex){
			BankLogUtils.printServiceImplExceptionLog(ex);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E6029);
		}
        return result;
	}

	@Override
	public Result bankBack(BaseMessage base) {
		Result result = new Result(false);
		UnionPayMessage message = new UnionPayMessage();
		BeanUtils.copyProperties(base, message);	
		try{
			boolean flag = (Boolean)unionPayManager.verify(message);
			result.setModel("message", message);
            result.setDefaultModel(flag);
            result.setSuccess(true);
            String amount = base.getAmount().toString();
        	amount = MoneyUtil.formatAmt(amount);
            if (result != null && result.isSuccess() && (Boolean) result.getDefaultModel()) {
            	Map<String, String> param = new HashMap<String, String>();
            	if(message.getRespCode() != null && message.getRespCode().equals(UnionPayConstants.TRAN_UNIONPAY_DEAL_SUCCESS)){
                    // 如果该订单成功通知后台地址入账                    
                    param.put("orderId", base.getOrderId());
                    param.put("amt", amount);
                    param.put("cardType", "Unknown");
                    param.put("notifyNum", "1");
                    param.put("payStatus", "00");
                    param.put("retCode", "00");
                    param.put("retMsg", "");
                    param.put("signData", message.getSignMessage());
                    param.put("isFront", base.isFront()+"");
                    result.setModel("isNotifyCashier", param);
                    result.setOrderStatus(true);
                    }
				else{
		             // 通知后台地址该订单失败
		             param.put("orderId", base.getOrderId());
		             param.put("amt", amount);
		             param.put("cardType", "Unknown");
		             param.put("notifyNum", "1");
		             param.put("payStatus", "01");
		             param.put("retCode", "01");
		             param.put("retMsg", "");
		             param.put("signData", message.getSignMessage());
		             param.put("isFront", base.isFront()+"");
		             result.setModel("isNotifyCashier", param);
		             result.setOrderStatus(false);
		     	}
            }
           
    	}catch(GopayException e){
    		BankLogUtils.printServiceImplExceptionLog(e);
    		result.setResultCode(e.getErrCode());
    	}catch(Exception ex){
			BankLogUtils.printServiceImplExceptionLog(ex);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E6064);
		}
		 return result;
	}

	@Override
	public Result query(BaseMessage base) {
		Result result = new Result(false);
		UnionPayMessage message = new UnionPayMessage();
		BeanUtils.copyProperties(base, message);
		try{
			message = (UnionPayMessage)unionPayManager.query(message);
            result.setDefaultModel(message);
            result.setSuccess(true);
            if(BisPayCheckUtils.checkExternalOrderID(base.getOrderId())){
        		Map<String, String> param = new HashMap<String, String>();
        		param.put("orderId", base.getOrderId());
        		param.put("amount", base.getAmount().toString());
        		if (message == null) {
        			// 查询订单为空
        			param.put("returnCode", BisPayConstants.QUERYSTATE_FAIL);
        			param.put("returnMessage", "银行返回对账结果为空");
        			param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
					result.setModel("queryResult", param);
					return result;
		        }
		        if (!StringUtils.equals(UnionPayConstants.TRAN_UNIONPAY_DEAL_SUCCESS, message.getRespCode())) {
        			// 查询订单错误
        			param.put("returnCode", BisPayConstants.QUERYSTATE_FAIL);
        			param.put("returnMessage", message.getRespMsg());
        			param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
					result.setModel("queryResult", param);
					return result;
		        }	
		        if(message.getQueryResult()!=null && !message.getQueryResult().equals("")){
			        // 成功处理
			        if (StringUtils.equals(UnionPayConstants.TRAN_UNIONPAY_DEAL_QUERY_SUCCESS, message.getQueryResult())) {
	    				param.put("returnCode", BisPayConstants.QUERYSTATE_SUCCESS);
						param.put("tradeState", BisPayConstants.TRADESTATE_SUCCESS);
						param.put("returnMessage", "交易成功");		            
			        }
			        //失败处理
			        else if(StringUtils.equals(UnionPayConstants.TRAN_UNIONPAY_DEAL_QUERY_FAIL, message.getQueryResult())){
	    				param.put("returnCode", BisPayConstants.QUERYSTATE_SUCCESS);
						param.put("tradeState", BisPayConstants.TRADESTATE_FAIL);
			            String errMsg = UnionPayOrderStatus.getName(message.getQueryResult());
			            if (errMsg != null) {
							param.put("returnMessage", errMsg);
			            } else {
							param.put("returnMessage", "银行返回交易失败");
			            }
			        }
			        else if(StringUtils.equals(UnionPayConstants.TRAN_UNIONPAY_DEAL_QUERY_DEALING, message.getQueryResult())){
			        	 // 银行订单状态为处理中
			        	param.put("returnCode", BisPayConstants.QUERYSTATE_SUCCESS);
						param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
			            String errMsg = UnionPayOrderStatus.getName(message.getQueryResult());
			            if (errMsg != null) {
							param.put("returnMessage", errMsg);
			            } else {
							param.put("returnMessage", "银行返回交易处理中");
			            }
			        }else if(StringUtils.equals(UnionPayConstants.TRAN_UNIONPAY_DEAL_QUERY_NO_TRANCTION, message.getQueryResult())){
			        	 // 银行查询无此记录
			        	param.put("returnCode", BisPayConstants.QUERYSTATE_SUCCESS);
						param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
			            String errMsg = UnionPayOrderStatus.getName(message.getQueryResult());
			            if (errMsg != null) {
							param.put("returnMessage", errMsg);
			            } else {
							param.put("returnMessage", "银行返回无此记录");
			            }
			        }
			        else {
			            param.put("returnCode", BisPayConstants.QUERYSTATE_SUCCESS);
						param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
			            String errMsg = UnionPayOrderStatus.getName(message.getQueryResult());
			            if (errMsg != null) {
							param.put("returnMessage", errMsg);
			            } else {
							param.put("returnMessage", "银行返回交易失败");
			            }
			        }
		        }
		        // 没有查到订单
				else {
					param.put("returnCode", BisPayConstants.QUERYSTATE_SUCCESS);
					param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
					param.put("returnMessage", "银行返回订单未查到");
				}
        		result.setModel("queryResult", param);
        	}
		}catch (GopayException e) {
			BankLogUtils.printServiceImplExceptionLog(e);
    		result.setResultCode(e.getErrCode());
		}catch(Exception ex){
			BankLogUtils.printServiceImplExceptionLog(ex);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E6033);
		}
		 return result;
	}

	@Override
	public Result refund(BaseMessage base) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Result dayend(BaseMessage base) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Result queryBack(BaseMessage base) {
		// TODO Auto-generated method stub
		return null;
	}

    @Override
    public Result refundBack(BaseMessage base) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Result refundQuery(BaseMessage base) {
        // TODO Auto-generated method stub
        return null;
    }

	@Override
	public Result sendBankRefund(BaseMessage base) {
		// TODO Auto-generated method stub
		return null;
	}

}
